/**
 *Copyright [2010] [lcj(caijunlu@gmail.com)]
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License. 
 *You may obtain a copy of the License at 
 *             http://www.apache.org/licenses/LICENSE-2.0 
 *Unless required by applicable law or agreed to in writing, 
 *software distributed under the License is distributed on an "AS IS" BASIS, 
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 *either express or implied. See the License for the specific language governing permissions and limitations under the License
 */
package org.independent.servlet.session.service;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


import org.independent.servlet.session.manager.ResponseCookie;

/**
 * the filter to get the request and response to put them to the ThreadLocal
 * 
 * @author lcj
 * 
 */
public class ContextFilter implements Filter {

	private ContextHolder serviceContextHolder;

	public void destroy() {
		serviceContextHolder.clearContext();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			serviceContextHolder.setContext(generateContext(request, response));
			chain.doFilter(request, response);
		} catch (IOException ioe) {
			throw ioe;
		} catch (ServletException se) {
			throw se;
		} finally {
			if (ContextHolderFactory.getServiceContextHolder().getContext()
					.getSessionIdCommitType() == 0
					&& response instanceof HttpServletResponse
					&& response != null
					&& ContextHolderFactory.getServiceContextHolder()
							.getContext().getSession() != null) {
				ResponseCookie.handleResponse((HttpServletResponse) response,
						ContextHolderFactory.getServiceContextHolder()
								.getContext().getSession().getId());
			}
		}
	}

	public void init(FilterConfig config) throws ServletException {

	}

	private Context generateContext(ServletRequest request,
			ServletResponse response) {
		Context context = new Context();
		context.setRequest(request);
		context.setResponse(response);
		return context;
	}
}
